import React, { useState, useCallback, useEffect } from 'react'
import { useHistory, useLocation } from 'react-router-dom'
import { getSofClientFindDropClient, getSysUserSelected } from '../../../Api/listUrl'
import {
    sysUploadUrl
} from '../../../Api/fileUrl';
import { putSofContractInsertContract, getSofContractAnswer, postSofContractUpdateContract } from '../Api'
import ItemMaterials from './Components/ItemMaterials'
import ItemModule from './Components/ItemModule'
import { AddContractAll } from './style'
import { PageHeader, Form, Input, Button, Typography, Row, Col, message, Select, DatePicker, InputNumber, Upload } from 'antd'
import moment from 'moment'
import { UploadOutlined } from '@ant-design/icons';

const { Title } = Typography;
const { Option } = Select;

/**
 * @description: 添加合同页面-编辑合同页面
 * @author: xiaoxujs
 * @updata: xiaoxujs（2021-07-20）
 * @updata: xiaoxujs（2021-11-20）销售人员改成输入联想，去掉合同负责人，签约时间不用必选
 */

const AddContract = () => {
    const history = useHistory()
    const location = useLocation()
    const { state } = location
    const [form] = Form.useForm()
    const { setFieldsValue, resetFields } = form
    const [clientList, setClientList] = useState([])
    const [userList, setUserList] = useState([])
    const [fileList, setFileList] = useState([]);
    const clientFun = useCallback(
        () => {
            ; (async () => {
                const { code, msg, data } = await getSofClientFindDropClient()
                if (code === '20000') {
                    setClientList(data)
                } else {
                    message.error(msg)
                }
            })()
        },
        [],
    )
    const userFun = useCallback(
        () => {
            ; (async () => {
                const { code, msg, data } = await getSysUserSelected()
                if (code === '20000') {
                    setUserList(data)
                } else {
                    message.error(msg)
                }
            })()
        },
        [],
    )
    useEffect(() => {
        clientFun()
        userFun()
        if (state) {
            ; (async () => {
                const { code, msg, data } = await getSofContractAnswer({ contractId: state.contractId })
                if (code === '20000') {
                    let newPdPlan = []
                    let allNum = 0
                    data.pdPlan.forEach(element => {
                        allNum = allNum + element.price * element.amount
                        newPdPlan.push({
                            product: element.product,
                            price: element.price,
                            amount: element.amount,
                            antEndDate: moment(element.antEndDate),
                            antStartDate: moment(element.antStartDate),
                        })
                    });
                    let newFileData = []
                    data.file.forEach(element => {
                        newFileData.push({
                            uid: element.path,
                            name: element.fileName,
                            status: 'done',
                            url: element.path,
                        })
                    });
                    const huixian = {
                        conNo: data.conNo,
                        clientId: data.clientId,
                        sellId: data.sellId,
                        mainId: data.mainId,
                        asMainId: data.asMainId,
                        concludeDate: moment(data.concludeDate),
                        item: data.item,
                        pdPlan: newPdPlan,
                        zongjine: allNum
                    }
                    setFileList(newFileData)
                    setFieldsValue(huixian)
                } else {
                    message.error(msg)
                }
            })()
        }
    }, [clientFun, userFun, state, setFieldsValue])
    const onFinish = (values) => {
        values.concludeDate = moment(values.concludeDate).format('YYYY-MM-DD')
        if (typeof values.pdPlan === 'undefined') {
            message.error('请添加产品信息!')
            return
        }
        for (let index = 0; index < values.pdPlan.length; index++) {
            values.pdPlan[index].antEndDate = moment(values.pdPlan[index].antEndDate).format('YYYY-MM-DD')
            values.pdPlan[index].antStartDate = moment(values.pdPlan[index].antStartDate).format('YYYY-MM-DD')
            values.pdPlan[index].conNo = values.conNo

        }
        values.file = []
        if (values.fileL) {
            for (let index = 0; index < values.fileL.fileList.length; index++) {
                const element = values.fileL.fileList[index];
                values.file.push(element.url)
            }
        } else if (fileList.length > 0) {
            fileList.forEach(element => {
                values.file.push(element.url)
            });

        } else {
            message.warning('请上传合同')
            return
        }
        delete values.zongjine
        delete values.fileL
        let show = false;
        if (values.item) {
            values.item.forEach((element, index) => {
                values.item.forEach((item, key) => {
                    if (index !== key && element.item === item.item) {
                        message.error('请确认收款方式是否重复！')
                        show = true
                    }
                });
            });
        } else {
            message.warning("请填写付款科目")
            return
        }

        if (show) {
            return
        }
        if (fileList.length <= 0) {
            message.error('请上传合同')
            return
        }
        if (state) {
            console.log(state);
            values.id = state.contractId
                ; (async () => {
                    const { code, msg } = await postSofContractUpdateContract(values)
                    if (code === '20000') {
                        message.success('修改成功');
                        resetFields()
                        history.go('-1')
                    } else {
                        message.error(msg)
                    }
                })()
        } else {
            ; (async () => {
                const { code, msg } = await putSofContractInsertContract(values)
                if (code === '20000') {
                    message.success('添加成功！');
                    resetFields()
                    history.go('-1')
                } else {
                    message.error(msg)
                }
            })()
        }

    };
    //获取总金额
    const handleAllMoney = (value) => {
        let all = 0;
        value.forEach(element => {
            all += element
        });
        setFieldsValue({ zongjine: all })
    }
    //上传附件
    const props = {
        name: 'file',
        action: sysUploadUrl(),
        fileList: fileList,
        headers: {
            authentication: sessionStorage.getItem("token")
        },
        data: {
            folder: '/client'
        },
        onChange(info) {
            let fileList = [...info.fileList];
            fileList = fileList.slice(-3);
            fileList = fileList.map(file => {
                if (file.response) {
                    file.url = file.response.data;
                }
                return file;
            });
            setFileList(fileList);
        },
    };
    return <AddContractAll>
        <PageHeader
            className="site-page-header"
            onBack={() => history.go('-1')}
            title={state ? '修改合同' : '添加合同'}
        />
        <Row >
            <Col xs={24} sm={24} md={24} lg={20} xl={12}>
                <Form
                    initialValues={{ yajinbili: 10 }}
                    onFinish={onFinish}
                    form={form}
                >
                    <Title level={3}>基本信息</Title>
                    <Row>
                        <Col span={24}>
                            <Form.Item
                                label="合同编号"
                                name="conNo"
                                rules={[{ required: true, message: '请输入合同编号!' }]}
                            >
                                <Input />
                            </Form.Item>
                        </Col>
                        <Col span={24}>
                            <Form.Item
                                label="客户"
                                name="clientId"
                                rules={[{ required: true, message: '请选择客户!' }]}
                            >
                                <Select
                                    showSearch
                                    optionFilterProp="children"
                                    filterOption={(input, option) =>
                                        option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }>
                                    {
                                        clientList.map(item => <Option value={item.id} key={item.id}>{item.clientName}</Option>)
                                    }
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={24}>
                            <Form.Item
                                label="销售人员"
                                name="sellId"
                                rules={[{ required: true, message: '请选择销售人员!' }]}
                            >
                                <Select
                                    showSearch
                                    filterOption={(input, option) =>
                                        option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }
                                >
                                    {
                                        userList.map(item => <Option value={item.id} key={item.id}>{item.name}</Option>)
                                    }
                                </Select>
                            </Form.Item>
                        </Col>
                        {/* <Col span={24}>
                            <Form.Item
                                label="合同负责人"
                                name="mainId"
                                rules={[{ required: true, message: '请选择负责人!' }]}
                            >
                                <Select>
                                    {
                                        userList.map(item => <Option value={item.id} key={item.id}>{item.name}</Option>)
                                    }
                                </Select>
                            </Form.Item>
                        </Col> */}
                        <Col span={24}>
                            <Form.Item
                                label="技术负责人"
                                name="asMainId"
                            // rules={[{ required: true, message: '请选择副负责人!' }]}
                            >
                                <Select>
                                    {
                                        userList.map(item => <Option value={item.id} key={item.id}>{item.name}</Option>)
                                    }
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={24}>
                            <Form.Item
                                label="签约时间"
                                name="concludeDate"
                            >
                                <DatePicker />
                            </Form.Item>
                        </Col>
                        {/* <Col span={24}>
                            <Form.Item
                                label="押金比例"
                                name="yajinbili"
                                rules={[{ required: true, message: '请输入押金比例!' }]}
                            >
                                <InputNumber
                                    min={0}
                                    max={100}
                                    formatter={value => `${value}%`}
                                    parser={value => value.replace('%', '')}
                                />
                            </Form.Item>
                        </Col> */}
                    </Row>
                    {/* 项目产品信息 */}
                    <ItemMaterials handleAllMoney={handleAllMoney} />
                    <Form.Item
                        label="总金额"
                        name="zongjine"
                        rules={[{ required: true, message: '自动输入!' }]}
                    >
                        <InputNumber />
                    </Form.Item>
                    {/* <Form.Item
                        label="收款科目"
                        name="item"
                        rules={[{ required: true, message: '请输入收款科目!' }]}
                    >
                        <Checkbox.Group options={ReceiptType} />
                    </Form.Item> */}
                    <ItemModule />
                    <Form.Item
                        label="上传合同"
                        name="fileL"
                    >
                        <Upload {...props}>
                            <Button icon={<UploadOutlined />}>上传合同</Button>
                        </Upload>
                    </Form.Item>


                    <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                        <Button type="primary" htmlType="submit">
                            提交
                        </Button>
                    </Form.Item>
                </Form>
            </Col>

        </Row>

    </AddContractAll >
}

export default AddContract